<template>
<!-- <section>的定义是：定义一个文档的章节 -->
  <section id="author">
    <el-card class="" shadow="never">
      <div slot="header">
        <span class="has-text-weight-bold">👨‍💻 关于作者</span>
      </div>

      <!-- 这里的user是发帖者 -->
      <div class="has-text-centered">
        <p class="is-size-5 mb-5">
          <router-link :to="{ path: `/member/${user.username}/home` }">
            {{ user.alias }} <span class="is-size-7 has-text-grey">{{ '@' + user.username }}</span>
          </router-link>
        </p>

        <div class="columns is-mobile">
          <div class="column is-half">
            <code>{{ user.topicCount }}</code>
            <p>文章</p>
          </div>
          <div class="column is-half">
            <code>{{ user.followerCount }}</code>
            <p>粉丝</p>
          </div>
        </div>

        <!-- 页面刷新完成后根据hasFollow是true表示已关注，否则未关注 -->
        <div>
          <button v-if="hasFollow" class="button is-success button-center is-fullwidth" @click="handleUnFollow(user.id)">已关注</button>
          <button v-else class="button is-link button-center is-fullwidth" @click="handleFollow(user.id)">关注</button>
        </div>
      </div>
    </el-card>
  </section>
</template>

<script>
import { follow, hasFollow, unFollow } from '@/api/follow'
import { mapGetters } from 'vuex'
export default {
  name: 'Author',
  props: {//父组件通过属性props向下传递数据给子组件，子组件通过事件events给父组件发送消息。
    user: {
      type: Object,
      default: null
    }
  },
  data() {//一个组件的data选项必须是一个函数
    return {
      hasFollow: false
    }
  },
  mounted() {//mounted在模板渲染成html后调用
    this.fetchInfo()
  },
  computed: {//computed用来监控自己定义的变量，购物车里面的商品列表和总金额之间的关系
    ...mapGetters([//引入mapGetters 我们就可以轻松的取到vuex中存储的数据
      'token'
    ])
  },
  methods: {
    fetchInfo() {
      if(this.token != null && this.token !== '')
      {
        hasFollow(this.user.id).then(value => {//用户已登录情况，向后端发接口查询关注状态是已关注还是未关注
          const { data } = value
          this.hasFollow = data.hasFollow
        })
      }else(
        console.log("该用户未登录，属于游客！")
      )
    },
    handleFollow: function(id) {
      if(this.token != null && this.token !== '')
      {
        follow(id).then(response => {
          const { message } = response
          this.$message.success(message)
          this.hasFollow = !this.hasFollow
          this.user.followerCount = parseInt(this.user.followerCount) + 1
        })
      }
      else{
        this.$message.success('请先登录')
      }
    },
    handleUnFollow: function(id) {
      unFollow(id).then(response => {
        const { message } = response
        this.$message.success(message)
        this.hasFollow = !this.hasFollow
        this.user.followerCount = parseInt(this.user.followerCount) - 1
      })
    }
  }
}
</script>

<style scoped>

</style>